package com.quanyan.search.service.impl;

import com.alibaba.dubbo.common.json.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.common.constants.SearchConstants;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.search.entity.request.ReqClubMemberInfo;
import com.quanyan.search.entity.response.ClubMemberResponse;
import com.quanyan.search.entity.response.SearchResponses;
import com.quanyan.search.entity.vo.ClubMemberIndexInfo;
import com.quanyan.search.service.ClubMemberSearchService;
import com.quanyan.search.utils.CommonUtil;
import com.quanyan.search.utils.SolrServerSingle;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.impl.CloudSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.MapSolrParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.util.*;

/**
 * ClubMemberSearchServiceImpl
 *
 * @author Tu Chun
 * @date 2016/6/29
 */
@Service
public class ClubMemberSearchServiceImpl implements ClubMemberSearchService {
    private static Logger logger = LoggerFactory.getLogger(ClubSearchServiceImpl.class);
    //public final static String URL = "192.168.30.75:2181,192.168.30.75:2182,192.168.30.75:2183";
    private String URL;

    public ClubMemberSearchServiceImpl(String URL) {
        this.URL = URL;
    }

    public ClubMemberSearchServiceImpl() {
    }

    public String getURL() {
        return URL;
    }

    public void setURL(String URL) {
        this.URL = URL;
    }



    /**
     * 添加俱乐部成员cy索引
     *
     * @param clubMemberIndexInfo
     * @return
     */
    @Override
    public APIResponse insertDoc(ClubMemberIndexInfo clubMemberIndexInfo) {

        try {
            if (addDocUtil(clubMemberIndexInfo)) {
                return APIResponse.returnSuccess("添加俱乐部成员" + clubMemberIndexInfo.getClub_member_nickname() + "索引c成功");
            } else {
                return APIResponse.returnFail("添加俱乐部成员");
            }
        } catch (Exception e) {
            logger.error(e.getMessage() + "添加俱乐部成员", e);
            return APIResponse.returnFail("添加俱乐部成员");
        }
    }

    /**
     * 添加多个俱乐部成员成员索引
     *
     * @param clubMemberIndexInfos
     * @return
     */
    @Override
    public APIResponse insertDocs(List<ClubMemberIndexInfo> clubMemberIndexInfos) {
        try {
            Long startTime=System.currentTimeMillis();
            Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            for (int i = 0; i < clubMemberIndexInfos.size(); i++) {
                ClubMemberIndexInfo indexInfo = clubMemberIndexInfos.get(i);
                //创建文档对象
                SolrInputDocument document = new SolrInputDocument();
                String uniqueId = SearchConstants.CLUB_MEMBER_ID_PREFIX + UUID.randomUUID().toString();
                document.addField("id", uniqueId);
                document.addField("club_member_uid", indexInfo.getClub_member_uid());
                document.addField("club_id_mem", indexInfo.getClub_id_mem());
                document.addField("club_member_nickname", indexInfo.getClub_member_nickname());
                document.addField("club_team_label_name", indexInfo.getClub_team_label_name());
                document.addField("club_role_name", indexInfo.getClub_role_name());
                solrServer.add(document);
                docs.add(document);
                logger.info("添加" + i + "号索引到文档中");
            }
            solrServer.add(docs);
            solrServer.commit();
            Long endTime=System.currentTimeMillis();
            logger.info("添加索引"+clubMemberIndexInfos.size()+"条执行时间："+((endTime-startTime)/(60*1000))+"分钟.");
            return APIResponse.returnSuccess("添加多个俱乐部成员索引成功");
        } catch (Exception e) {
            logger.error(e.getMessage() + "添加多个俱乐部成员索引异常", e);
            return APIResponse.returnFail("添加多个俱乐部成员索引失败");
        }
    }

    /**
     * 根据id删除Document
     *
     * @param club_id
     * @param club_member_uid
     * @return
     */
    @Override
    public APIResponse deleteDocById(Integer club_id, Integer club_member_uid) {
        try {
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            StringBuilder stringBuilder = new StringBuilder();
            if(CommonUtil.isNullOrZero(club_id) || CommonUtil.isNullOrZero(club_member_uid)){
                return APIResponse.returnFail("俱乐部id、俱乐部成员id不能为空");
            } else if (!CommonUtil.isNullOrZero(club_id) && !CommonUtil.isNullOrZero(club_member_uid)) {
                stringBuilder.append("club_id_mem:").append(club_id);
                stringBuilder.append(" AND club_member_uid:").append(club_member_uid);
            }

            solrServer.deleteByQuery(stringBuilder.toString());
            solrServer.commit();
            return APIResponse.returnSuccess("删除俱乐部成员索引成功");
        } catch (Exception e) {
            logger.error(e.getMessage() + "删除俱乐部成员索引异常", e);
            return APIResponse.returnFail("删除俱乐部成员引失败");
        }
    }
    /**
     * 根据id搜索俱乐部成员成员信息
     *
     * @param club_id
     * @param club_member_uid
     * @return
     */
    @Override
    public APIResponse<ClubMemberIndexInfo> searchClubMemberInfo(Integer club_id, Integer club_member_uid) {
        try {
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            Map<String, String> params = new HashMap<String, String>();
            StringBuilder stringBuilder = new StringBuilder();
            if(CommonUtil.isNullOrZero(club_id) || CommonUtil.isNullOrZero(club_member_uid)){
                return APIResponse.returnFail("俱乐部id、俱乐部成员id不能为空");
            } else if (!CommonUtil.isNullOrZero(club_id) && !CommonUtil.isNullOrZero(club_member_uid)) {
                stringBuilder.append("club_id_mem:").append(club_id);
                stringBuilder.append(" AND club_member_uid:").append(club_member_uid);
            }

            params.put("q", stringBuilder.toString());
            QueryResponse response = solrServer.query(new MapSolrParams(params), SolrRequest.METHOD.POST);
            SolrDocumentList solrDocumentList = response.getResults();
            List<ClubMemberIndexInfo> clubMemberIndexInfos = response.getBeans(ClubMemberIndexInfo.class);
            //List<PlaceSearchResponse> responses=getPlaceSearchResponseList(placeIndexInfoList,null,null);
            return APIResponse.returnSuccess(CommonUtil.isNullOrZero(clubMemberIndexInfos) ? null : clubMemberIndexInfos.get(0));
        } catch (Exception e) {
            logger.error(e.getMessage() + "根据id搜索俱乐部成员异常", e);
            return APIResponse.returnFail("根据id搜索俱乐部成员失败");
        }
    }

    /**
     * 根据条件搜索
     *
     * @param reqClubMemberInfo
     * @return
     */
    @Override
    public APIResponse<List<ClubMemberResponse>> searchClubMemberInfoList(ReqClubMemberInfo reqClubMemberInfo) {
        try {
            SearchResponses<List<ClubMemberResponse>> searchResponses = new SearchResponses<List<ClubMemberResponse>>();
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            Map<String, String> params = new HashMap<String, String>();
            //俱乐部成员id
            Integer club_id = reqClubMemberInfo.getClub_id();
            //俱乐部成员用户id
            Integer club_member_uid = reqClubMemberInfo.getClub_member_uid();
            //俱乐部成员成员名字
            String club_member_name = reqClubMemberInfo.getClub_member_nickname();


            Integer pageNo = reqClubMemberInfo.getPageNo();
            Integer pageSize = reqClubMemberInfo.getPageSize();
            Integer startPosition = pageNo * pageSize;
            StringBuilder builder = new StringBuilder();
            if (!StringUtil.isBlankOrNull(club_member_name)) {
                builder.append("(club_member_nickname:").append(club_member_name + "^1.9");
                builder.append(" OR club_member_nickname:").append(club_member_name +"*"+ "^1.9)");
            } else {
                builder.append("club_member_nickname:*");

            }
            if(!CommonUtil.isNullOrZero(club_id)){
                builder.append(" AND club_id_mem:").append(club_id);
            }
            logger.warn("query:" + builder.toString());
            params.put("q", builder.toString());
            params.put("start", startPosition.toString());//记录开始位置
            params.put("rows", pageSize.toString());//查询的行数
            params.put("df", "club_member_keywords");   // 设置默认搜索域
            //设置高亮
           /* params.put("hl", "true");
            params.put("hl.fl", "club_member_nickname");
            params.put("hl.simple.pre", "<em style=\"color:red\">");
            params.put("hl.simple.post", "</em>");*/
            QueryResponse response = solrServer.query(new MapSolrParams(params), SolrRequest.METHOD.POST);
            SolrDocumentList solrDocumentList = response.getResults();
            long total = solrDocumentList.getNumFound();
            //取高亮显示
           // Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
            //List<PlaceIndexInfo> placeIndexInfoList = response.getBeans(PlaceIndexInfo.class);
            List<ClubMemberResponse> clubResList = getClubMemberSearchResponseList(solrDocumentList, null);
            /*searchResponses.setData(clubResList);
            searchResponses.setPageNo(pageNo);
            searchResponses.setPageSize(pageSize);
            searchResponses.setTotal((int)total);*/
            return APIResponse.returnSuccess(clubResList);
        } catch (Exception e) {
            logger.error(e.getMessage() + "搜索数据异常", e);
            return APIResponse.returnFail("搜索数据异常");


        }

    }

    private List<ClubMemberResponse> getClubMemberSearchResponseList(SolrDocumentList solrDocumentList, Map<String, Map<String, List<String>>> highlighting) throws ParseException, IOException {
        List<ClubMemberResponse> clubSearchResponses = new ArrayList<ClubMemberResponse>();
        List<ClubMemberIndexInfo> clubMemberIndexInfos = new ArrayList<ClubMemberIndexInfo>();

        for (SolrDocument solrDocument : solrDocumentList) {
            ClubMemberIndexInfo indexInfo = new ClubMemberIndexInfo();
            //解析solr中数据
            String id = (String) solrDocument.get("id");
            String club_id = (String) solrDocument.get("club_id_mem");
            String club_member_uid = (String) solrDocument.get("club_member_uid");
            String club_member_nickname = (String) solrDocument.get("club_member_nickname");
            String club_team_label_name = (String) solrDocument.get("club_team_label_name");
            String club_role_name = (String) solrDocument.get("club_role_name");
            //取高亮显示的结果
            /*List<String> list = highlighting.get(solrDocument.get("id")).get("club_member_nickname");
            if (list != null && list.size() > 0) {
                club_member_nickname = list.get(0);
            } else {
                club_member_nickname = (String) solrDocument.get("club_member_nickname");
            }
            */
            List<Date> startDateList = new ArrayList<Date>();


            //测试打印数据
            indexInfo.setId(id);
            indexInfo.setClub_id_mem(club_id);
            indexInfo.setClub_member_uid(club_member_uid);
            indexInfo.setClub_member_nickname(club_member_nickname);
            indexInfo.setClub_team_label_name(club_team_label_name);
            indexInfo.setClub_role_name(club_role_name);
            clubMemberIndexInfos.add(indexInfo);


            //封装返回的数据
            ClubMemberResponse clubMemberRes = new ClubMemberResponse();
            clubMemberRes.setClub_id(Integer.parseInt(club_id));
            clubMemberRes.setClub_member_uid(club_member_uid);
            clubMemberRes.setClub_team_label_name(club_team_label_name);
            clubMemberRes.setClub_role_name(club_role_name);

            clubSearchResponses.add(clubMemberRes);
        }
        //测试打印数据
        logger.warn("clubMemberIndexInfo-size:" + clubMemberIndexInfos.size());
        logger.warn("clubMemberIndexInfo:" + JSON.json(clubMemberIndexInfos));

        return clubSearchResponses;

    }

    private boolean addDocUtil(ClubMemberIndexInfo indexInfo) {
        try {
            //创建连接
            CloudSolrServer solrServer = SolrServerSingle.getInstance(URL);
            // 设置默认的collection
            solrServer.setDefaultCollection("collection2");
            //创建文档对象
            SolrInputDocument document = new SolrInputDocument();
            String uniqueId = SearchConstants.CLUB_MEMBER_ID_PREFIX + UUID.randomUUID().toString();
            document.addField("id", uniqueId);
            document.addField("club_member_uid", indexInfo.getClub_member_uid());
            document.addField("club_id_mem", indexInfo.getClub_id_mem());
            document.addField("club_member_nickname", indexInfo.getClub_member_nickname());
            document.addField("club_team_label_name", indexInfo.getClub_team_label_name());
            document.addField("club_role_name", indexInfo.getClub_role_name());
            solrServer.add(document);
            solrServer.commit();
            logger.info("添加俱乐部成员索引成功");
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage() + "添加俱乐部成员成员索引失败", e);
            return false;

        }
    }

}
